<template>
  <a-form ref="formRef" :model="formState" :rules="rules" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
    <a-form-item v-for="item in formStateMap" :key="item.key" :ref="item.key" :label="item.label" :name="item.key">
      <!-- 输入框 -->
      <a-input v-if="item.type == 'input'" v-model:value="formState[item.key as formKeys]" :placeholder="`请填写${item.label}`" />
      <!-- 选择框 -->
      <a-select v-else-if="item.type == 'select'" v-model:value="formState[item.key as formKeys]" style="width: 180px">
        <a-select-option v-for="classification in classificationMap" :key="classification._id" :value="classification._id">
          {{ classification.name }}
        </a-select-option>
      </a-select>
      <!-- 富文本 -->
      <RichText v-else v-model:value="formState[item.key as formKeys]" height="320px" />
    </a-form-item>
    <a-form-item class="submit-item">
      <a-button type="primary" block @click="handleSubmit">确定</a-button>
    </a-form-item>
  </a-form>
</template>
<script lang="ts" setup>
import { reactive, ref, onMounted } from "vue"
import type { Rule } from "ant-design-vue/es/form"
import { useRoute } from "vue-router"
import { notification } from "ant-design-vue"
import { assignProperties } from "@/utils"
import { addCase, getAllCaseCategory, getCaseInfo, updateCase } from "@/api/case"
import RichText from "@/components/RichText/index.vue"
import type { OralCaseItem } from "@/api/case/type"

interface FormStateMap {
  key: string
  label: string
  value: string
  type: string
}
type formKeys =
  | "name"
  | "classification_id"
  | "Medifood_recipe"
  | "desc"
  | "thumbs"
  | "video"
  | "indication"
  | "treated_disease"
  | "Medifood_usage"
  | "Medifood_aroma"
  | "Medifood_color"
  | "Medifood_flavor"
  | "Edible_method"
  | "Associated_symptoms"
  | "treatment_site"
  | "Medifood_classify"

const formRef = ref()
const route = useRoute()
const classificationMap = ref<any>([])

const formState: OralCaseItem = reactive({
  name: "",
  classification_id: "",
  Medifood_recipe: "",
  desc: "",
  // thumbs: [
  //   { title: "CT", content: [], key: "CT", closable: false },
  //   { title: "MRI", content: [], key: "MRI" }
  // ],
  thumbs: "",
  video: "",
  indication: "",
  treated_disease: "",
  Medifood_usage: "",
  Medifood_aroma: "",
  Medifood_color: "",
  Medifood_flavor: "",
  Edible_method: "",
  Associated_symptoms: "",
  treatment_site: ""
})
const formStateMap: Array<FormStateMap> = [
  { key: "Medifood_classify", label: "药膳类型", value: "", type: "rich-text" },
  { key: "name", label: "药膳名称", value: "", type: "input" },
  { key: "classification_id", label: "分类", value: "", type: "select" },
  // { key: "desc", label: "药膳基本描述", value: "", type: "input" },
  { key: "thumbs", label: "药膳图片", value: "", type: "image" },
  { key: "video", label: "药膳视频", value: "", type: "video" },
  { key: "Medifood_recipe", label: "药膳配方", value: "", type: "rich-text" },
  { key: "indication", label: "适应症", value: "", type: "rich-text" },
  { key: "Medifood_usage", label: "用法", value: "", type: "rich-text" },
  { key: "treated_disease", label: "治疗疾病", value: "", type: "rich-text" },
  { key: "Medifood_aroma", label: "药膳香味", value: "", type: "rich-text" },
  { key: "Medifood_color", label: "药膳颜色", value: "", type: "rich-text" },
  { key: "Medifood_flavor", label: "药膳味道", value: "", type: "rich-text" },
  { key: "Associated_symptoms", label: "关联症状", value: "", type: "rich-text" },
  { key: "Edible_method", label: "食用方法", value: "", type: "rich-text" },
  { key: "treatment_site", label: "治疗部位", value: "", type: "rich-text" }
]
const rules: Record<string, Rule[]> = {
  name: [
    { required: true, message: "请输入药膳名称", trigger: "blur" },
    { min: 1, max: 24, message: "姓名长度为 2至24", trigger: "blur" }
  ],
  classification_id: [{ required: true, message: "请选择药膳分类", trigger: "blur" }]
}
onMounted(async () => {
  let { id } = route.query
  // 编辑时，回填数据
  if (id) {
    let { code, data } = await getCaseInfo(id as string)
    if (code == 0) {
      assignProperties(formState, data)
    } else {
      notification.error({
        message: "系统提醒",
        description: "数据加载失败，请重试"
      })
    }
  }
  let { code, data } = await getAllCaseCategory()
  if (code == 0) {
    classificationMap.value = data
  }
})
const handleSubmit = () => {
  let values: OralCaseItem = JSON.parse(JSON.stringify(formState))
  console.log("图片格式", values.thumbs)
  console.log("视频格式", values.video)

  // 确保 values.thumbs 是一个字符串
  values.thumbs = (values.thumbs || "").toString()
  values.video = (values.video || "").toString()

  values.thumbs = extractImageUrls(values.thumbs)
  values.video = extractVideoUrls(values.video)
  console.log("图片url", values.thumbs)
  console.log("视频url", values.video)

  formRef.value.validate().then(async () => {
    const { id } = route.query
    let res: any = {}
    if (!id) {
      res = await addCase(values)
    } else {
      res = await updateCase(id as string, values)
    }
    if (res.code == 0) {
      notification.success({
        message: res.message
      })
    } else {
      notification.error({
        message: res.message
      })
    }
  })
}

// 提取图片 URL 并返回逗号分隔的字符串
const extractImageUrls = (html: string): string => {
  const imgRegex = /<img[^>]+src="([^">]+)"/g
  const urls: string[] = []
  let match
  while ((match = imgRegex.exec(html)) !== null) {
    console.log("匹配到的图片 URL:", match[1]) // 调试信息
    urls.push(match[1])
  }
  return urls.join(",") // 返回逗号分隔的字符串
}
// 提取视频 URL 并返回逗号分隔的字符串
const extractVideoUrls = (html: string): string => {
  const videoRegex = /<source[^>]+src="([^">]+)"/g
  const urls: string[] = []
  let match
  while ((match = videoRegex.exec(html)) !== null) {
    console.log("匹配到的视频 URL:", match[1]) // 调试信息
    urls.push(match[1])
  }
  return urls.join(",") // 返回逗号分隔的字符串
}
defineExpose({ formState })
</script>
<style lang="scss" scoped>
:deep(.ant-form-item-label label) {
  font-size: 12px;
}
.select {
  width: 160px;
}
:deep(.select .ant-select-selector) {
  font-size: 12px;
}
:deep(.submit-item .ant-row) {
  display: flex;
  justify-content: center;
}
</style>
